import {DELETED_CLASS, HIDDEN_SELECTED_ELEM_ID, HIGHLIGHT_CLASS} from "~utils/constants";
import uuidWrapper from "~utils/uuid";
import {stringifyHighlighsToViewstate} from "~manager/viewstateManager";
import {initializeHighlightEventListeners} from "~contents/hoverTools";
import { store } from "~storage/store";

const create = async (color) => {
  console.log("inside highlightImage create...");
  const elem = document.getElementById(HIDDEN_SELECTED_ELEM_ID);
  console.log(elem.innerText);
  const highlightImageElem = Array.from(document.getElementsByTagName("img")).filter(item => item.src === elem.innerText)[0];

  const url = location.hostname + location.pathname;
  const highlightWithViewstate = await buildHighlightImage(highlightImageElem.src, url, location.href, color.color, "");
  highlightImageElem.classList.add((color === 'inherit') ? DELETED_CLASS : HIGHLIGHT_CLASS);
  highlightImageElem.dataset.highlightId = highlightWithViewstate.uuid;
  highlightImageElem.textContent = highlightWithViewstate.imageSrc;
  highlightImageElem.setAttribute("viewstate", highlightWithViewstate.viewstate);
  initializeHighlightEventListeners(highlightImageElem);

  await store(url, highlightWithViewstate.viewstate);
}

const buildHighlightImage = (imageSrc, url, href, color, comments) => {
  const highlight = {
    uuid: uuidWrapper(),
    imageSrc: imageSrc,
    imageName: "图片",
    color,
    href,
    ver: "*ver_image*",
    comments, // JM: comments must be the last one if in array (not here)
  }

  highlight.viewstate = stringifyHighlighsToViewstate(highlight);

  // Return the index of the new highlight:
  return highlight;
}

export default create;
